<?php

namespace App\Http\Controllers\App\V1;

use App\Http\Controllers\App\Rebuild\PublicApiController;
use App\Models\MainDB\UserAuthBlacklist;
use Carbon\Carbon;
use App\Response\Response;
use App\Enums\SmsTypeEnum;
use App\Services\Tools\JwtService;
use App\Services\Tools\SmsService;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;        //引用http请求类
use App\Exceptions\BasicException;  //引入框架异常处理类

class AuthController extends BaseController {

    public function process(Request $request) {
        $input = $request->all();
        //参数校验
        $v = app('validator')->make($input, [
            'certName' => 'required',
            'certNo'   => 'required',
            'code'     => 'required',
            'hold'     => 'required',
            'front'    => 'required',
            'back'     => 'required',
        ]);
        if ($v->fails()) throw new BasicException(20005);
        if (!checkCertNo($input['certNo'])) {
            throw new BasicException(20003);
        }
        if(!isAdult($input['certNo']))
        {
            throw new BasicException(120003);
        }

        if (!app('redis')->exists(PublicApiController::user_blacklist_IdNumber)) {
            PublicApiController::userList("IdNumber");
        }
        $user_blacklist_IdNumber_list = app('redis')->get(PublicApiController::user_blacklist_IdNumber);
        if (in_array($input['certNo'],json_decode($user_blacklist_IdNumber_list,true))){
            throw new BasicException(-1, "已加入实名黑名单");
        }

        $token = $request->header('token', '');
        $user_id = JwtService::getUid($token, true);
        $mobile = app('repo_user')->getUserMobile($user_id);
        if (!$mobile) {
            throw new BasicException(20009);
        }

        if (env('APP_ENV_SMS') == 'production') {
            if (!SmsService::verify($mobile, $input['code'], SmsTypeEnum::AUTH_MANUAL)) {
                throw new BasicException(20010);
            }
        }
        $detail = app('repo_user_auth')->getUserAuth($user_id);
        if ($detail) {
            if ($detail->app_status == 0) {
                throw new BasicException(20007);
            } elseif ($detail->app_status == 1) {
                throw new BasicException(20008);
            }
        }

        // 验证身份证号是否被拉黑
        $isBan = UserAuthBlacklist::query()->where("id_number", $input['certNo'])->exists();
        if($isBan){
            throw new BasicException(-1, "已加入实名黑名单");
        }

        $result = app('model_user_auth')->create([
            'user_id'   => $user_id,
            'full_name' => $input['certName'],
            'id_number' => $input['certNo'],
            'id_card'   => $input['hold'],
            'front'     => $input['front'],
            'back'      => $input['back'],
        ]);
        if (!$result) {
            throw new BasicException(90001);
        }

        return Response::sendData('申请成功，请等待审核');
    }

    public function sendSms(Request $request) {
        $user_id = JwtService::getUid($request->header('token', true));
        $mobile = app('repo_user')->getUserMobile($user_id);
        if (!$mobile) {
            throw new BasicException(20009);
        }
        $type = $request->input('type', 1);
        $key = 'get:sms:auth:' . $type . ':' . $mobile;
        $times = Cache::get($key);
        if ($times >= 10) {
            throw new BasicException(20011);
        }
        SmsService::send($mobile, $type == 1 ? 9 : 10);
        Cache::put($key, $times + 1, Carbon::tomorrow());

        return Response::sendData('发送成功');
    }

    public function result() {
        $result = app('repo_user_auth')->getUserAuth(UID);
        if (!$result) {
            $app_status = 3;
            $reason = '';
            $info = '您还未提交实名认证';
        } else {
            switch ($result->app_status) {
                case 0:
                    $info = '审核中';
                    break;
                case 1:
                    $info = '通过';
                    break;
                case 2:
                    $info = '审核不通过' . ($result->reason ? ': ' . $result->reason : '');
                    break;
                default:
                    $result->app_status = 0;
                    $info = '审核中';
            }
            $app_status = $result->app_status;
            $reason = $result->reason ?? '';
        }
        return Response::sendData(['app_status' => $app_status, 'reason' => $reason, 'message' => $info]);
    }
}
